﻿using ERPWinFormWork.Material.Material.Dtos;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Material
{
    public partial class Order : Form
    {
        public string SelectedWorkNumber { get; private set; }
        public string SelectedWorkName { get; private set; }

        public Order()
        {
            InitializeComponent();
            _apiClient = new ApiClient(MaterialAppConfig.ApiBaseUrl);
            InitializeDataGridView();
            GetData();
            
            // 绑定按钮事件
            btnsure1.Click += Btnsure1_Click;
            btnoff.Click += Btnoff_Click;
        }

        /// <summary>
        /// 确定按钮点击事件
        /// </summary>
        private void Btnsure1_Click(object sender, EventArgs e)
        {
            // 查找选中的行
            for (int i = 0; i < dgvorder.Rows.Count; i++)
            {
                DataGridViewCheckBoxCell checkBoxCell = dgvorder.Rows[i].Cells[0] as DataGridViewCheckBoxCell;
                if (checkBoxCell != null && checkBoxCell.Value != null && (bool)checkBoxCell.Value)
                {
                    // 获取选中行的数据
                    SelectedWorkNumber = dgvorder.Rows[i].Cells[1].Value?.ToString() ?? ""; // 工单编号
                    SelectedWorkName = dgvorder.Rows[i].Cells[2].Value?.ToString() ?? ""; // 工单名称
                    
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                    return;
                }
            }
            
            MessageBox.Show("请先选择一条记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 关闭按钮点击事件
        /// </summary>
        private void Btnoff_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        /// <summary>
        /// 初始化DataGridView，添加复选框列
        /// </summary>
        private void InitializeDataGridView()
        {
            // 清空现有列
            dgvorder.Columns.Clear();
            
            // 添加复选框列
            DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
            checkBoxColumn.HeaderText = "选择";
            checkBoxColumn.Name = "CheckBoxColumn";
            checkBoxColumn.Width = 50;
            dgvorder.Columns.Add(checkBoxColumn);
            
            // 添加工单编号列
            DataGridViewTextBoxColumn workNumberColumn = new DataGridViewTextBoxColumn();
            workNumberColumn.HeaderText = "工单编号";
            workNumberColumn.Name = "WorkNumberColumn";
            workNumberColumn.DataPropertyName = "Work_Number";
            workNumberColumn.Width = 150;
            dgvorder.Columns.Add(workNumberColumn);
            
            // 添加工单名称列
            DataGridViewTextBoxColumn workNameColumn = new DataGridViewTextBoxColumn();
            workNameColumn.HeaderText = "工单名称";
            workNameColumn.Name = "WorkNameColumn";
            workNameColumn.DataPropertyName = "Work_Name";
            workNameColumn.Width = 200;
            dgvorder.Columns.Add(workNameColumn);
            
            // 添加任务负责人列
            DataGridViewTextBoxColumn taskLeaderColumn = new DataGridViewTextBoxColumn();
            taskLeaderColumn.HeaderText = "任务负责人";
            taskLeaderColumn.Name = "TaskLeaderColumn";
            taskLeaderColumn.DataPropertyName = "Task_Leader";
            taskLeaderColumn.Width = 150;
            dgvorder.Columns.Add(taskLeaderColumn);
            
            // 设置复选框列只能单选
            dgvorder.CellClick += Dgvorder_CellClick;
        }

        /// <summary>
        /// DataGridView单元格点击事件，实现单选功能
        /// </summary>
        private void Dgvorder_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex >= 0) // 点击复选框列
            {
                // 取消其他行的选中状态
                for (int i = 0; i < dgvorder.Rows.Count; i++)
                {
                    if (i != e.RowIndex)
                    {
                        dgvorder.Rows[i].Cells[0].Value = false;
                    }
                }
                
                // 设置当前行复选框状态
                bool currentValue = dgvorder.Rows[e.RowIndex].Cells[0].Value == null ? false : (bool)dgvorder.Rows[e.RowIndex].Cells[0].Value;
                dgvorder.Rows[e.RowIndex].Cells[0].Value = !currentValue;
            }
        }

        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 2;
        private int TotalCount { get; set; } = 0;
        private int TotalPages { get; set; } = 0;

        public class ApiResponse<T>
        {
            public int code { get; set; }
            public string message { get; set; }
            public string jwt { get; set; }
            public T pageData { get; set; }
            public T data { get; set; }
            public int totalCount { get; set; }
            public int totalPages { get; set; }
        }

        private ApiClient _apiClient;

        private async void GetData(Dictionary<string, string> customParams = null)
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                };

            // 合并自定义参数（查询条件）
            if (customParams != null)
            {
                foreach (var kv in customParams)
                {
                    parameters[kv.Key] = kv.Value;
                }
            }
            var response = await _apiClient.GetAsync<ApiResponse<List<Work_recordOutput>>>(
                    endpoint: "Material/GetWork_recordShow",
                    parameters: parameters // 传递查询参数
                );
            // 处理响应结果
            if (response != null && response.code == 200)
            {
                // 将数据绑定到 DataGridView
                dgvorder.DataSource = response.pageData;
                
                // 初始化复选框列的值
                foreach (DataGridViewRow row in dgvorder.Rows)
                {
                    row.Cells[0].Value = false;
                }
            }
        }
    }
}
